jQuery(function(){
	///新建联系记录
	jQuery('.dealBtn').on('click',function(){
		var selects=getSelect("#planTable",1);
	    if(selects.length==0){
	    	message("请先选择一个维护计划");
	    	return;
	    }
		jQuery('#id').val('');
		jQuery('#contact').val('');
		jQuery('#contactWay').val('');
		jQuery('#contactResult').val('');
		jQuery('#contactTime').val('');
		jQuery('#contactContent').val('');
		jQuery('#memo1').val('');
		jQuery('#contactModal').modal('show');
	})

	//获取通知记录页面数据 服务器分页
	var serverContactData = {};
	var	serverContactTable;
	jQuery(document).ready(function () {
		serverContactTable = jQuery('#contactTable').DataTable({
			"serverSide": true,
			"ordering": false,
			"ajax": {
				"dataType": "json",
				"type": "get",
				"cache": false,
				"url":window.rootPath+ '/ui/aftersaleactive/getPage',
				"data": function (d) {
					return $.extend({}, d, serverContactData);
				}
			},
			columns: [
				{
					data: null
				},
				{
					data: null,
					defaultContent: "",
					render: function (data, type, full, meta) {
						var id=data.contractId
						var operate ='<input type="checkbox" class="checkcontactchild">';
						return operate;
					}
				},
				{
					data: 'contactTime',
					render: function (data, type, full, meta) {
						if (data)
							return moment(data).format('YYYY-MM-DD');
						else
							return '';
					}
				},
				{
					data: 'contact'
				},
				{
					data: 'contactWay'
				},
				{
					data: 'operator'
				},
				{
					data: 'contactResult'
				},
				{
					data: 'contactContent'
				},
				{
					data: 'memo1',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 10) ? '<font title="'+data+'">'+data.substring(0,10)+'...'+'</font>' : data;
						}
					}
				},

			],
			"drawCallback": function (oSettings) {
				var k = 0;
				var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

				for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
					$('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
					k++;
				}
				 serverTable.off('click','tr');
		         serverTable.on( 'click', 'tr', function (event) {
		                event=event||window.event;
		                var target=event.target||event.scrElement;
		                var data = serverTable.row( this ).data();
		                jQuery('#contractID').val(data.contractId);
		                serverPlanData.contractID=data.contractId;
		                serverPlanTable.draw();
		                return ;
		            } );
			}
		});
	});



	//编辑通知记录信息
	jQuery('.editContactBtn').on('click', function () {
		var selects=getSelect("#contactTable",1);
		if(selects.length>1){
			$.springLemonDialog({
				content: '只能编辑一条记录',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		}
		else if(selects.length==0){
			$.springLemonDialog({
				content: '请选择要编辑的记录',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		}else if(selects.length==1) {
			jQuery('#id').val(selects[0].id);
			jQuery('#contact').val(selects[0].contact);
			jQuery('#contactWay').val(selects[0].contactWay);
			jQuery('#operator').val(selects[0].operator);

			var createTime=selects[0].createTime;
			jQuery('#contactResult').val(selects[0].contactResult);
			if (selects[0].contactTime) {
				var time = moment(selects[0].contactTime).format('YYYY-MM-DD');
				jQuery('#contactTime').val(time);
			}
			jQuery('#contactContent').val(selects[0].contactContent);
			jQuery('#memo1').val(selects[0].memo1);
			jQuery('#contactModal').modal('show');
		};
	});

	//添加/编辑通知记录 保存
	var $btn = jQuery('.saveContactBtn').on('click', function () {
		if(jQuery("#contactForm") && !jQuery("#contactForm").Validform({tiptype:3, showAllError:true}).check(false)){
			return;
		};
		var isId=jQuery("#id").val();
		var contact = jQuery('#contact').val();
		var contactWay = jQuery('#contactWay').val();
		var createTime = jQuery('#createTime').val();
		var operator=jQuery('#operator').val();
		var contactResult = jQuery('#contactResult').val();
		var contactTime = jQuery('#contactTime').val();
		var contactContent = jQuery('#contactContent').val();
		var memo1 = jQuery('#memo1').val();
		jQuery(".saveContactBtn").attr("disabled", true);
		//判断是编辑还是新增
		if(isId == ""){
			var api = window.rootPath + "/ui/aftersaleactive/saveContact";
			var d = {
				"contact": contact,
				"contactWay": contactWay,
				"operator": operator,
				"contactResult": contactResult,
				"contactTime": contactTime,
				"contactContent": contactContent,
				"memo1": memo1
			};
			jQuery.ajax({
				type: 'post',
				url: api,
				data: JSON.stringify(d),
				dataType: 'json',
				contentType: 'application/json;charset=utf-8',
				success: function (data) {
					{
						var selects=getSelect("#planTable",1);
						if(selects.length==0){
							$.springLemonDialog({
								content: '请选择要处理的计划',// 确认文本
								clickButton: function (sender, modal, index) {// 按钮事件处理
									$(this).closeDialog(modal);
								}
							});
						}else {
							var ids=selects[0].planId;
							for(var i=1;i<selects.length;i++){
								ids += ',' + selects[i].planId;
							}
							$.springLemonDialog({
								content: '已保存一条通知记录，确认处理'+selects.length+'条计划？',// 确认文本
								clickButton: function deal(sender, modal, index) {// 按钮事件处理
									if (index == 0) {
										var url=window.rootPath+"/ui/aftersaleactive/dealPlan/" + ids;
										jQuery.ajax({
											url:encodeURI(url),
											cache:false,
											type : "get",
											dataType:"json",
											success:function(data){
												serverTable.draw(false);
												jQuery('#contractID').val(selects[0].contractID);
												serverPlanData.contractID=selects[0].contractID;
												serverPlanTable.draw(false);
											}
										});
									}
									$(this).closeDialog(modal);
								}
							});
						}
					}
					jQuery('#contactModal').modal('hide');
					serverContactTable.draw(true);
					var contractID=jQuery('#contractID').val();
					jQuery(".saveContactBtn").attr("disabled", false);
					delTask(contractID,"维护超期");
				}
			});

		}
		else{
			var data={
				contact:jQuery('#contact').val(),
				contactWay:jQuery('#contactWay').val(),
				createTime:createTime,
				operator:jQuery('#operator').val(),
				contactResult:jQuery('#contactResult').val(),
				contactTime:jQuery('#contactTime').val(),
				contactContent:jQuery('#contactContent').val(),
				memo1:jQuery('#memo1').val()
			};
			var url=window.rootPath+'/api/noticeRecords/'+isId;
			jQuery.ajax({
				url:encodeURI(url),
				type:'patch',
				data:JSON.stringify(data),
				dataType:'json',
				contentType:'application/json;charset=utf-8',
				success: function () {
					jQuery('#contactModal').modal('hide');
					serverContactTable.draw(false);
					jQuery(".saveContactBtn").attr("disabled", false);
				}

			});
		}
	});
	//获取主动售后数据 服务器分页
	var serverData = {};
	var	serverTable;
	jQuery(document).ready(function () {
		serverTable = jQuery('#activeTable').DataTable({
			"serverSide": true,
			"ordering": false,
			"ajax": {
				"dataType": "json",
				"type": "get",
				"cache": false,
				"url":window.rootPath+ '/ui/aftersaleactive/getpage',
				"data": function (d) {
					return $.extend({}, d, serverData);
				}
			},
			columns: [
				{
					data: null
				},
				{
					data: null,
					defaultContent: "",
					render: function (data, type, full, meta) {
						var operate ='<input type="checkbox" class="checkchildContact">';
						return operate;
					}
				},
				{
					data: 'supplierCode'
				},
				{
					data: 'projectName'
				},
				{
					data: 'orderUnit'
				},
				{
					data: 'servicingTime',
					render: function (data, type, full, meta) {
						if (data)
							return moment(data).format('YYYY-MM-DD');
						else
							return '';
					}
				},
				{
						data: null,
	                	 render: function (data, type, full, meta) {
		                        var dOut;
		                        if(data.state=="已超期"){
		                            dOut = '<td class="center" ><span class="badge label-pill label-danger">已超期</span></td>';
		                        }     
		                        else if(data.outState=="正常") {
		                            dOut = '<td class="center" ><span class="badge label-pill label-primary">正常</span></td>';
		                        }   
		                        
		                        return dOut;
		                    }
				},
				{
					data: 'memo',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 20) ? '<font title="'+data+'">'+data.substring(0,20)+'...'+'</font>' : data;
						}
					}
				},

			],
			"drawCallback": function (oSettings) {
				var k = 0;
				var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

				for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
					$('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
					k++;
				}
			}
		});
	});
	//添加主动售后信息，弹窗清空
	jQuery('.addBtn').on('click', function () {
		jQuery('#id').val('');
		jQuery('#supplierCode').val('');
		jQuery('#projectName').val('');
		jQuery('#orderUnit').val('');
		jQuery('#servicingTime').val('');
		jQuery('#state').val('');
		jQuery('#memo').val('');
		//RemoveItem();
		//getSupplierCode();
		jQuery('#activeModal').modal('show');
	});
	
	//编辑主动售后信息
	jQuery('.editBtn').on('click', function () {
		var selects=getSelect("#activeTable",1);
		if(selects.length>1){
			$.springLemonDialog({
				content: '只能编辑一条记录',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		}
		else if(selects.length==0){
			$.springLemonDialog({
				content: '请选择要编辑的记录',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		}else if(selects.length==1) {
			jQuery('#activeId').val(selects[0].id);
			jQuery('#activesupplierCode').val(selects[0].supplierCode);
			jQuery('#activeorderUnit').val(selects[0].orderUnit);
			jQuery('#activeprojectName').val(selects[0].projectName);
			if (selects[0].servicingTime) {
				var time = moment(selects[0].servicingTime).format('YYYY-MM-DD');
				var s1=jQuery('#activeservicingTime').val(time);
			}
			var ss=jQuery('#activestate').val(selects[0].state);
			var m=jQuery('#activememo').val(selects[0].memo);
			var ac=jQuery('#activeEditModal').modal('show');
		};
	});
	//列表中的全选
	$("#checkAll").click(function(){
		var check = $(this).prop("checked");
		$(".checkchild").prop("checked", check);
	});

	$("#checkcontactAll").click(function(){
		var check = $(this).prop("checked");
		$(".checkcontactchild").prop("checked", check);
	});

	///下拉框选择客户信息////
	jQuery('#supplierCode').trigger('change');///自动触发下拉框

	jQuery('#supplierCode').change(function(){
		var supplierCode=jQuery(this).children('option:selected').val();
		var url=window.rootPath+"/ui/contract/getContractBySupplierCode"+"?supplierCode="+supplierCode;
		jQuery.ajax({
			url:  encodeURI(url),
			cache:false,
			type: 'get',
			dataType: 'json',
			success: function (data) {
				var contractID = data.contract.id;
				var orderUnit = data.contract.orderUnit;
				var projectName = data.contract.projectName;
				jQuery('#contractID').val(contractID);
				jQuery('#orderUnit').val(orderUnit);
				jQuery('#projectName').val(projectName);
				serverData.contractID = contractID;
				serverTable.draw();
			}
		});

	})

	//新增保存主动售后信息
	var $btn = jQuery('.saveBtn').on('click', function () {
		if(jQuery("#activeEditForm") && !jQuery("#activeEditForm").Validform({tiptype:3, showAllError:true}).check(false)){
			return;
		};
		var iId=jQuery("#id").val();
		var contractID=jQuery('#contractID').val();
		var supplierCode = jQuery('#supplierCode').val();
		var projectName = jQuery('#projectName').val();
		var orderUnit=jQuery('#orderUnit').val();
		var servicingTime = jQuery('#servicingTime').val();
		var state = jQuery('#state').val();
		var memo = jQuery('#memo').val()
			var api = window.rootPath + "/ui/aftersaleactive/save/"+contractID;
			var d = {
				"supplierCode": supplierCode,
				"projectName": projectName,
				"orderUnit": orderUnit,
				"servicingTime": servicingTime,
				"state": state,
				"isAfterSaleActive":true,
				"memo": memo
			};
			jQuery.ajax({
				type: 'post',
				url: api,
				data: JSON.stringify(d,{}),
				dataType: 'json',
				contentType: 'application/json;charset=utf-8',
				success: function (data) {
					var selTarget = document.getElementById("supplierCode");
					if(selTarget.selectedIndex > -1)
					{//说明选中
						for(var i=0;i<selTarget.options.length;i++)
						{
							if(selTarget.options[i].selected)
							{
								selTarget.remove(i);
								i = i - 1;
							}
						}
					}
					jQuery('#activeModal').modal('hide');
					serverTable.draw(true);
				}
			});
	})
//编辑保存主动售后信息
	var $btn = jQuery('.saveactiveBtn').on('click', function () {

		var isId=jQuery("#activeId").val();
		var contractID=jQuery('#contractID').val();
		var activesupplierCode = jQuery('#activesupplierCode').val();
		var activeprojectName = jQuery('#activeprojectName').val();
		var activeorderUnit=jQuery('#activeorderUnit').val();
		var activeservicingTime = jQuery('#activeservicingTime').val();
		var activestate = jQuery('#activestate').val();
		var activememo = jQuery('#activememo').val()
		var data={
				"supplierCode": activesupplierCode,
				"projectName": activeprojectName,
				"orderUnit": activeorderUnit,
				"servicingTime": activeservicingTime,
				"state": activestate,
				"memo": activememo
			};
			var url=window.rootPath+'/api/afterSaleActives/'+isId;
			jQuery.ajax({
				url:encodeURI(url),
				type:'patch',
				data:JSON.stringify(data),
				dataType:'json',
				contentType:'application/json;charset=utf-8',
				success: function () {
					jQuery('#activeEditModal').modal('hide');
					serverTable.draw(false);
				}

			});
	})

	//获取当前泵的维护计划 服务器分页
	var serverPlanData = {};
	var serverPlanTable;
	jQuery(document).ready(function () {
		serverPlanTable = jQuery('#planTable').DataTable({
			"serverSide": true,
			"ordering": false,
			"iDisplayLength": 5,
			"ajax": {
				"dataType": "json",
				"type": "get",
				"cache": false,
				"url": window.rootPath + '/ui/aftersaleactive/getContractPlan',
				"data": function (d) {
					return $.extend({}, d, serverPlanData);
				}
			},
			columns: [
				{
					data: null
				},
				{
					data: null,
					defaultContent: "",
					render: function (data, type, full, meta) {
						var id = data.id
						var operate = '<input type="checkbox" class="checkchild">';
						return operate;
					}
				},
				{
					data: 'leaveFactoryCode'
				},
				{
					data: 'createTime',
					render: function (data, type, full, meta) {
						if (data)
							return moment(data).format('YYYY-MM-DD');
						else
							return '';
					}
				},
				{
					data: 'startDate',
					render: function (data, type, full, meta) {
						if (data)
							return moment(data).format('YYYY-MM-DD');
						else
							return '';
					}
				},
				{
					data: 'maintainPeriod'
				},
				{
					data: 'maintainProject'
				},
				{
					data: 'announcement'
				},
				{
					data: null,
					render: function (data, type, full, meta) {
						var dOut;
		                if(data.state=="正常"){
		                    dOut = '<td class="center" ><span class="badge label-pill label-primary">正常</span></td>';
		                }     
		                else if(data.state=="已超期") {
		                    dOut = '<td class="center" ><span class="badge label-pill label-danger">已超期</span></td>';
		                }
		                return dOut;
					}
				},
				{
					data: 'memo',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 20) ? '<font title="'+data+'">'+data.substring(0,20)+'...'+'</font>' : data;
						}
					}
				}
			],
			"drawCallback": function (oSettings) {
				var k = 0;
				var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

				for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
					$('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
					k++;
				}
				
			}
		});
	});




	jQuery('.checkBtn').on('click', function () {
		var selects=getSelect("#activeTable",1);
		if(selects.length>1){
			$.springLemonDialog({
				content: '只能查看一条记录',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		}
		else if(selects.length==0){
			$.springLemonDialog({
				content: '请选择要查看的记录',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		}else if(selects.length==1) {
			jQuery('#contractID').val(selects[0].contractId);
			serverPlanData.contractID=selects[0].contractId;
			serverPlanTable.draw();
		};
	});

	//jQuery('.dealBtn').on('click', function () {
	//	var selects=getSelect("#planTable",1);
	//	if(selects.length==0){
	//		$.springLemonDialog({
	//			content: '请选择要处理的计划',// 确认文本
	//			clickButton: function (sender, modal, index) {// 按钮事件处理
	//				$(this).closeDialog(modal);
	//			}
	//		});
	//	}else {
	//		var ids=selects[0].planId;
	//		for(var i=1;i<selects.length;i++){
	//			ids += ',' + selects[i].planId;
	//	}
	//		$.springLemonDialog({
	//			content: '确认处理'+selects.length+'条记录？',// 确认文本
	//			clickButton: function (sender, modal, index) {// 按钮事件处理
	//				if (index == 0) {
	//					var url=window.rootPath+"/ui/aftersaleactive/dealPlan/" + ids;
	//					jQuery.ajax({
	//						url:encodeURI(url),
	//						cache:false,
	//						type : "get",
	//						dataType:"json",
	//						success:function(data){
	//							serverTable.draw(false);
	//							jQuery('#contractID').val(selects[0].contractID);
	//							serverPlanData.contractID=selects[0].contractID;
	//							serverPlanTable.draw(false);
	//						}
	//					});
	//				}
	//				$(this).closeDialog(modal);
	//			}
	//		});
	//    }
	//});




	//查询
	jQuery('.searchBtn').on('click',function(){
		serverData.key=jQuery('#keyword').val();
		serverTable.draw();
	})
	//撤销查询
	jQuery('.resetBtn').on("click",function()
	{
		jQuery('#keyword').val('');
		serverData.key ='';
		serverTable.draw();
	});
	////删除售后合同,不删除合同本身，只是不在这个列表显示，删除后可以再次添加
	jQuery('.delBtn').on('click', function () {
		var selects=getSelect("#dataTable",1);
		var url=window.rootPath+"/ui/afterSaleDeviceInfo/delContract";
		delSelect(selects,url,serverTable)
	});

	//删除通知记录
	jQuery('.delContactBtn').on('click', function () {
		var selects=getSelect("#contactTable",1);
		var url=window.rootPath+"/ui/aftersaleactive/delContact";
		delSelect(selects,url,serverContactTable)
	});

	//查询
	jQuery('.searchContactBtn').on('click',function(){
		serverContactData.key=jQuery('#keywordContact').val();
		serverContactTable.draw();
	})
	//撤销查询
	jQuery('.resetContactBtn').on("click",function()
	{
		jQuery('#keywordContact').val('');
		serverContactData.key ='';
		serverContactTable.draw();
	});

	///////维护计划中的全选
	$("#checkAll").click(function(){
		var check = $(this).prop("checked");
		$(".checkchild").prop("checked", check);
	});


	///////通知记录中的全选
	$("#checkcontactAll").click(function(){
		var check = $(this).prop("checked");
		$(".checkchildContact").prop("checked", check);
	});
});
